package org.playground.booking.auth.provider;

import org.playground.booking.auth.entity.Customer;
import org.playground.booking.auth.entity.Merchant;
import org.playground.booking.auth.entity.Role;
import org.playground.booking.auth.entity.User;
import org.playground.booking.auth.enums.PlaygroundUserRoles;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class PGBookingUserDetails implements UserDetails{
    private User user;
    private static String ROLE_PREFIX="ROLE_";

    private List<GrantedAuthority> authorities;


    public PGBookingUserDetails(User user){
        this.user = user;
        authorities = new ArrayList<GrantedAuthority>();
        if(user instanceof Customer){
            //there is only one role for customer, which is customer
            PlaygroundUserRoles role = PlaygroundUserRoles.CUSTOMER;
            GrantedAuthority authority = new SimpleGrantedAuthority(ROLE_PREFIX+role.getRole());
            authorities.add(authority);
        }else if(user instanceof Merchant){
            for(Role role : ((Merchant)user).getRolesList()){
                GrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
                authorities.add(authority);
            }
        }
    }



    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}